package com.ins1st.core.aspect;

import com.ins1st.api.SysServiceLogApi;
import com.ins1st.core.annotation.Log;
import com.ins1st.entity.SysServiceLog;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @program: ins1st-cloud
 * @description:
 * @author: coderSun
 * @create: 2019-11-19 14:46
 **/
@Aspect
@Component
public class LogAspect {

    @Autowired
    private SysServiceLogApi sysServiceLogApi;

    @Pointcut("@annotation(com.ins1st.core.annotation.Log)")
    private void cut() {
    }

    @Before("cut()")
    public void before(JoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Class clazz = methodSignature.getDeclaringType();
        Method method = methodSignature.getMethod();
        Log log = method.getAnnotation(Log.class);
        String value = log.value();
        String service = log.service();
        String params = log.params();
        SysServiceLog sysServiceLog = new SysServiceLog();
        sysServiceLog.setServiceName(StringUtils.isBlank(service) ? "未知服务" : service);
        sysServiceLog.setLogName(StringUtils.isBlank(value) ? "未知业务" : value);
        sysServiceLog.setMethodName(method.getName());
        sysServiceLog.setClassName(clazz.getName());
        if (StringUtils.isNotBlank(params)) {
            String[] parr = params.split(",");
            StringBuilder sb = new StringBuilder("[");
            for (String param : parr) {
                sb.append(param);
                sb.append(":");
                sb.append(request.getParameter(params));
                sb.append(",");
            }
            sb.append("]");
            sysServiceLog.setMethodParams(sb.toString());
        }
        sysServiceLog.setLogTime(new Date());
        this.sysServiceLogApi.insert(sysServiceLog);


    }
}
